package com.area.cth.service.impl;

import com.area.cth.mapper.PostMapper;
import com.area.cth.common.PageBean;
import com.area.cth.pojo.CommentPost;
import com.area.cth.pojo.Post;
import com.area.cth.pojo.Thumb;
import com.area.cth.service.PostService;
import com.area.cth.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Autowired
    private PostMapper pm;

    @Override
    public void addPost(Post p) {
        p.setCreateTime(LocalDateTime.now());
        p.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        p.setCreateUser(id);
        pm.addPost(p);
    }

    @Override
    public List<Post> getPostList() {
        return pm.getPostList();
    }

    @Override
    public Post getPostById(Integer id) {
        return pm.getPostById(id);
    }

    @Override
    public List<Post> getMyPostList() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        return pm.getMyPostList(id);
    }

    @Override
    public void updatePost(Post p) {
        p.setUpdateTime(LocalDateTime.now());
        pm.updatePost(p);
    }

    @Override
    @Transactional
    public void deletePost(Integer id) {
        //删除评论表中相关记录
        LambdaQueryWrapper<CommentPost> commentWrapper=new LambdaQueryWrapper<CommentPost>()
                .eq(CommentPost::getPostId,id);
        Db.remove(commentWrapper);

        //删除点赞表中相关记录
        LambdaQueryWrapper<Thumb> thumbWrapper=new LambdaQueryWrapper<Thumb>()
                .eq(Thumb::getPostId,id);
        Db.remove(thumbWrapper);

        pm.deletePost(id);
    }

    @Override
    public List<Post> searchPost(String keyword) {
        return pm.searchPost(keyword);
    }

    @Override
    public List<Post> getPostByUserList(Integer userId) {
        return pm.getPostByUserList(userId);
    }

    @Override
    public PageBean<Post> postList(Integer pageNo, Integer pageSize) {
        Page<Post> page=Page.of(pageNo, pageSize);
        Page<Post> p=lambdaQuery()
                .page(page);
        PageBean<Post> pb=new PageBean<>();
        pb.setTotal(p.getTotal());
        pb.setPages(p.getPages());
        pb.setRecords(p.getRecords());
        return pb;
    }
}
